<template>
  <div class="app-container">
    <el-form
      ref="ruleForm"
      :inline="true"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-card class="box-card">
        <div>
          <el-form-item
            label="通知名称："
            prop="bannerName"
          >
            <el-input
              v-model="ruleForm.bannerName"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="banner图："
            prop="imageUrl"
          >
            <el-upload
              v-model="ruleForm.imageUrl"
              class="upload-demo"
              :action="imagesUploadApi"
              :limit="1"
              :headers="headers"
              :on-change="handleChange"
              :file-list="fileList"
            >
              <el-button
                size="small"
                type="text"
              >上传</el-button>
            </el-upload>
            <img v-if="this.$route.query.bannerId" style="width: 200px; height: 200px;" :src="ruleForm.imageUrl" alt="">
            <!-- <el-button
              size="small"
              type="text"
            >上传</el-button> -->
          </el-form-item>
        </div>
      </el-card>
      <el-card style="margin-top: 20px;">
        <div
          slot="header"
          class="clearfix"
        >
          <span>说明文档</span>
        </div>
        <el-form-item>
          <div ref="editor" class="editor" />
          <!-- {{ ruleForm.docContent }}
          </div> -->
        </el-form-item>
      </el-card>
      <el-form-item style="margin-top: 10px">
        <el-button
          v-if="!this.$route.query.bannerId"
          type="primary"
          @click="submitForm('ruleForm')"
        >确定</el-button>
        <el-button
          v-if="this.$route.query.bannerId"
          type="primary"
          @click="editForm('ruleForm')"
        >确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { upload } from '@/utils/upload'
import crudHelp from '@/api/help'
import E from 'wangeditor'
import { addPaint, editBanners } from '@/api/help'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
var editor = null
export default {
  name: 'AddPaint',
  data() {
    return {
      ruleForm: {
        bannerName: '',
        docContent: '',
        imageUrl: ''
      },
      show: false,
      headers: {
        'Authorization': getToken()
      },
      fileList: [],
      rules: {
        bannerName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '请上传', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  created() {
    if (this.$route.query.bannerId) {
      crudHelp.getBanners({
        bannerId: this.$route.query.bannerId
      }).then((res) => {
        this.ruleForm = res.content[0]
        this.createData()
      })
    } else {
      this.ruleForm = {
        bannerName: '',
        docContent: '',
        imageUrl: ''
      }
      this.fileList = []
      this.createData()
    }
  },
  methods: {
    inEditor() {
      const _this = this
      editor = new E(this.$refs.editor)
      // 自定义菜单配置
      editor.config.zIndex = 10
      // 文件上传
      editor.config.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
        files.forEach(image => {
          upload(_this.imagesUploadApi, image).then(res => {
            const data = res.data
            const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
            insert(url)
          })
        })
      }
      editor.config.onchange = (html) => {
        this.ruleForm.docContent = html
      }
      editor.create()
    },
    createData() { // 新建或者编辑回显
      this.$nextTick(() => { // 使用 this.$nextTick 获取焦点
        this.inEditor() // 调用上面写的方法
        editor.txt.html(this.ruleForm.docContent) // 向富文本中插入回显的数据
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          await addPaint(this.ruleForm)
          this.$message.success('添加成功')
          this.$refs.ruleForm.resetFields()
          this.ruleForm.docContent = ''
          this.ruleForm.imageUrl = ''
          this.fileList = []
          this.$router.go(-1)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    editForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          await editBanners(this.ruleForm)
          this.$message.success('修改成功')
          this.$refs.ruleForm.resetFields()
          this.ruleForm.docContent = ''
          this.ruleForm.imageUrl = ''
          this.fileList = []
          this.$router.go(-1)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3)
      if (this.fileList[0].response) {
        this.ruleForm.imageUrl = this.baseApi + '/file/' + this.fileList[0].response.type + '/' + this.fileList[0].response.realName
      }
    },
    cancel() {
      this.$refs.ruleForm.resetFields()
      this.fileList = []
      this.$router.go(-1)
    }
  }
}
</script>

  <style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    height: calc(100vh - 50px);
    overflow: auto;
  }
  ::v-deep(.el-button--text) {
    border: 0;
    padding: 0;
    width: 60px;
    background-color: #fff;
    color: #1890ff;
  }
  </style>

